package 算法

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha1"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"fmt"
)

// 加密
func EncryptOAEP(text,publicKey []byte)(string,error) {
	rsaPublicKey := ParsePKIXPublicKey(publicKey)
	secretMessage := text
	rng := rand.Reader
	cipherdata, err := rsa.EncryptOAEP(sha1.New(), rng, rsaPublicKey, secretMessage, nil)
	if err != nil {
		//fmt.Fprintf(os.Stderr, "Error from encryption: %s\n", err)
		return "",err
	}
	ciphertext := base64.StdEncoding.EncodeToString(cipherdata)
	//fmt.Printf("Ciphertext: %x\n", ciphertext)
	return ciphertext,nil
}

// 解密
func DecryptOAEP(ciphertext string,publicKey []byte) (string,error) {
	rsaPrivateKey := ParsePKCS1PrivateKey(publicKey)
	cipherdata, _ := base64.StdEncoding.DecodeString(ciphertext)
	rng := rand.Reader
	plaintext, err := rsa.DecryptOAEP(sha1.New(), rng, rsaPrivateKey, cipherdata, nil)
	if err != nil {
		//fmt.Fprintf(os.Stderr, "Error from decryption: %s\n", err)
		return "",err
	}
	//fmt.Printf("Plaintext: %s\n", string(plaintext))
	return string(plaintext),nil
}

// 解析公钥
func ParsePKIXPublicKey(publicKey []byte) *rsa.PublicKey {
	//publicKey, err := ioutil.ReadFile("static/cert/apiclient_cert.pem")
	//if err != nil {
	//	fmt.Println(err)
	//	return nil
	//}
	block, _ := pem.Decode(publicKey)
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return pubInterface.(*rsa.PublicKey)
}

// 解析私钥
func ParsePKCS1PrivateKey(privateKey []byte) *rsa.PrivateKey {
	//privateKey, err := ioutil.ReadFile("static/cert/apiclient_key.pem")
	//if err != nil {
	//	fmt.Println(err)
	//	return nil
	//}
	block, _ := pem.Decode(privateKey)
	privateInterface, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return privateInterface
}
